package com.imooc.mall.controller;

import com.imooc.mall.consts.MallConst;
import com.imooc.mall.form.UserLoginForm;
import com.imooc.mall.form.UserRegisterForm;
import com.imooc.mall.pojo.User;
import com.imooc.mall.service.IUserService;
import com.imooc.mall.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author: bizy
 * @date: 2020/07/12 19:29
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/user/register")
    public ResponseVO<User> register(@Valid @RequestBody UserRegisterForm userForm) {
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        return userService.register(user);
    }

    @PostMapping("/user/login")
    public ResponseVO<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
                                  HttpServletRequest httpServletRequest) {
        ResponseVO<User> userResponseVO = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());

        //设置session
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute(MallConst.CURRENT_USER,userResponseVO.getData());

        return userResponseVO;
    }

    @GetMapping("/user")
    public ResponseVO<User> userInfo(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        User user = (User)session.getAttribute(MallConst.CURRENT_USER);
        return ResponseVO.success(user);
    }

    /**
     * {@link TomcatServletWebServerFactory} getSessionTimeoutInMinutes
     */
    @PostMapping("/user/logout")
    public ResponseVO logout(HttpSession session) {
        log.info("/user/logout sessionId={}",session.getId());

        session.removeAttribute(MallConst.CURRENT_USER);
        return ResponseVO.success();
    }

}
